<script setup lang="ts">
import { Upload, Download } from "@element-plus/icons-vue";
import {
  FormInfo,
  FormInfoInput,
  MatchTable,
  InfoContainer
} from "@/views/resourceAccess/components";
import { reactive, ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { formInfo } from "../components/interface";
import { EditTable, Log } from "./components";
import { clone } from "@pureadmin/utils";
import { Icon } from "@iconify/vue";
import axios from "axios";
import { message } from "@/utils/message";
import { socket } from "../egdeCloud/socket";
const sleep = (ms: number) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};
const formProps1: formInfo = reactive({
  title: "数据标识",
  btnNames: ["生成数据标识", undefined, undefined],
  btnDisabled: [false, false, false],
  formInfoList: [
    {
      id: 1,
      title: "选择数据集",
      inputType: "1",
      placeholder: "选择要分配标识的数据或数据集",
      options: [
        {
          value: "选择要分配标识的数据或数据集",
          label: "选择要分配标识的数据或数据集"
        }
      ]
    }
  ]
});
const formProps2: formInfo = reactive({
  formInfoList: [
    {
      id: 2,
      title: "企业名称",
      inputType: "0",
      options: [
        {
          value: "浪潮工业互联网",
          label: "浪潮工业互联网"
        }
      ]
    },
    {
      id: 3,
      title: "应用场景",
      inputType: "0",
      options: [
        {
          value: "个性化定制",
          label: "个性化定制"
        }
      ]
    },
    {
      id: 4,
      title: "边缘网关",
      inputType: "0",
      options: [
        {
          value: "边缘网关01",
          label: "边缘网关01"
        }
      ]
    },
    {
      id: 5,
      title: "设备ID",
      inputType: "0",
      options: [
        {
          value: "设备ID",
          label: "设备ID"
        }
      ]
    },
    {
      id: 6,
      title: "数据类型",
      inputType: "0",
      options: [
        {
          value: "设备状态数据",
          label: "设备状态数据"
        }
      ]
    }
  ]
});
const tableDatas = reactive({
  array: [
    {
      colInfo: [
        { labelName: "企业名称", dataProps: ["data1"] },
        { labelName: "企业节点标识前缀", dataProps: ["data2"] }
      ],
      tableData: [
        {
          data1: "浪潮",
          data2: "MA.10000.900000.00000003"
        },
        {
          data1: "致景",
          data2: "MA.10000.900000.00000019"
        }
      ]
    },
    {
      colInfo: [
        { labelName: "应用场景编码（1位）", dataProps: ["data1"] },
        {
          labelName: "支持数字1-9，字母a-z，A-Z，最多61种编码",
          dataProps: ["data2"]
        }
      ],
      tableData: [
        {
          data1: "1",
          data2:
            "浪潮基于协同研发的产品个性化定制场景、济南浪潮智能终端生产基地"
        },
        {
          data1: "2",
          data2:
            "浪潮基于协同研发的产品个性化定制场景、济南浪潮智能终端生产基地"
        },
        {
          data1: "3",
          data2: "致景基于云边协同的产品质量检测场景，四川宜宾致景纺织智造园"
        },
        {
          data1: "4",
          data2: "致景基于云边协同的产品质量检测场景，四川宜宾致景纺织智造园"
        }
      ]
    },
    {
      colInfo: [
        { labelName: "边缘网关编码（2位）", dataProps: ["data1"] },
        {
          labelName:
            "支持01-99，最多99个边缘网关采集点，如需拓展，可使用字母a-z，A-Z拓展",
          dataProps: ["data2"]
        }
      ],
      tableData: [
        {
          data1: "01",
          data2: "产线1区采集点"
        },
        {
          data1: "02",
          data2: "产线2区采集点"
        }
      ]
    },
    {
      colInfo: [
        { labelName: "设备ID编码（8位）", dataProps: ["data1"] },
        {
          labelName: "设备ID自增表，当设备查询无结果时自动添加",
          dataProps: ["data2"]
        }
      ],
      tableData: [
        {
          data1: "00000001",
          data2: "e_af01c45020934134a5e2b123bd3ea0c1"
        },
        {
          data1: "00000002",
          data2: "e_42284b93dfdf42eb9c58b00670845f2b"
        }
      ]
    },
    {
      colInfo: [
        {
          labelName: "数据类型编码（1位）",
          dataProps: ["data1"]
        },
        {
          labelName: "支持数字1-9，字母a-z，A-Z，最多61种编码",
          dataProps: ["data2"]
        }
      ],
      tableData: [
        {
          data1: "1",
          data2: "设备状态数据"
        },
        {
          data1: "2",
          data2: "图片"
        },
        {
          data1: "3",
          data2: "音频"
        },
        {
          data1: "4",
          data2: "文档如txt等"
        },
        {
          data1: "5",
          data2: "视频"
        },
        {
          data1: "6",
          data2: "其它"
        }
      ]
    }
  ]
});
const logDatas = reactive({
  array: []
});
const ip = "10.8.58.1:6443";
const topic = "topicDataLake2-json";

const editTable = ref(false); //点击主页面的编辑按钮
// drawer配置
const drawerVisible = ref(false);
const drawer_props = reactive({
  title: "数据标识配置映射表"
});
const leftContentTitle = "数据推送日志";
const kafkaConfig = ref(null);
const SDID = ref(null);
const scrollBarRef = ref(null),
  innerBarRef = ref(null);

const downLoadToolTip = ref("从云端下载配置映射表到本地");
const upLoadToolTip = ref("更新配置映射表到云端");
const syncData = () => {
  const getTableData = (tableData, flag) => {
    let options = [];
    for (let item in tableData) {
      if (tableData[item]["id"] == undefined) {
        tableData[item]["id"] = (Number(item) + 1).toString();
      }
      options.push({
        label: tableData[item][flag],
        value: JSON.stringify([
          tableData[item]["data1"],
          tableData[item]["data2"]
        ])
      });
    }
    return options;
  };
  const syncDataSingle = (tableData, flag: number) => {
    let options = [];
    if (tableData == undefined && tableData.length == 0) {
      return [];
    }

    if (flag == 0) {
      options = getTableData(tableData, "data2");
    } else {
      options = getTableData(tableData, "data1");
    }

    return options;
  };
  for (let item in tableDatas.array) {
    if (tableDatas.array[item].colInfo[0].labelName == "企业名称") {
      formProps2.formInfoList[item].options = syncDataSingle(
        tableDatas.array[item].tableData,
        1
      );
    } else {
      formProps2.formInfoList[item].options = syncDataSingle(
        tableDatas.array[item].tableData,
        0
      );
    }
  }
};
const formBtnClick = async e => {
  const getCurrentTimestamp = () => {
    let current_time = new Date();
    return `${current_time.getFullYear().toString().slice(2)}${(current_time.getMonth() + 1).toString().padStart(2, "0")}${current_time.getDate().toString().padStart(2, "0")}${current_time.getHours().toString().padStart(2, "0")}${current_time.getMinutes().toString().padStart(2, "0")}${current_time.getSeconds().toString().padStart(2, "0")}`;
  };
  const getCurrentTime = () => {
    // 创建一个新的 Date 对象，表示当前时间
    const now = new Date();
    // 获取年、月、日、时、分、秒
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
    const day = String(now.getDate()).padStart(2, "0");
    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    const seconds = String(now.getSeconds()).padStart(2, "0");
    // 格式化时间字符串
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

    return formattedTime;
  };
  const enterprise = JSON.parse(kafkaConfig.value[0].value)[1];
  const scene = JSON.parse(kafkaConfig.value[1].value)[0];
  const gateway = JSON.parse(kafkaConfig.value[2].value)[0];
  const deviceId = JSON.parse(kafkaConfig.value[3].value)[0];
  const dataType = JSON.parse(kafkaConfig.value[4].value)[0];
  const timeStamp = getCurrentTimestamp();
  const dataCode = `${enterprise}/${scene}${gateway}${deviceId}${dataType}/${timeStamp}`;
  SDID.value.inputValue = dataCode;
  // send msg----------------------------------------------
  const fileName = e[1][0].fileName;
  const fileData = e[1][0].fileData;
  const sendMsg = {
    fileName: fileName,
    fileData: fileData,
    enterprise: enterprise,
    scene: scene,
    gateway: gateway,
    deviceId: deviceId,
    dataType: dataType,
    timeStamp: timeStamp,
    dataCode: dataCode
  };
  console.log("待发送数据：", sendMsg);
  message("正在推送中...", {
    type: "info",
    customClass: "antd",
    
  });
  socket.emit(
    "send_kafka_msg",
    {
      msg: JSON.stringify(sendMsg),
      topic: topic
    },
    async res => {
      message("推送成功", { type: "success", customClass: "antd" });
      logDatas.array.unshift({
        timeStamp: getCurrentTime(),
        topic: topic,
        ip: ip.split(":")[0],
        port: ip.split(":")[1],
        fileName: fileName,
        dataCode: dataCode
      });
      await nextTick();
      scrollBarRef.value!.setScrollTop(0);
    }
  );
  // ----------------------------------------------send msg
};
syncData();
const dataListRef = ref(null);
const dataList = ref([]);
const columnsName = ref([]);
const tableIndex = ref(-1);

const tableBtnClick = (index: number) => {
  const list_data = [],
    list_name = [];
  const tableData = clone(tableDatas.array[index].tableData, true);
  const colInfo = clone(tableDatas.array[index].colInfo, true);
  for (let item in colInfo) {
    list_name.push(colInfo[item].labelName);
  }
  for (let item in tableData) {
    list_data.push(tableData[item]);
  }
  dataList.value = list_data;
  // console.log("click", list_data, dataList.value);

  columnsName.value = list_name;
  editTable.value = true;
  tableIndex.value = index;
};
const closeEdit = () => {
  console.log("ref", dataListRef.value.dataList);
  tableDatas.array[tableIndex.value].tableData = dataListRef.value.dataList;
  const curRow = dataListRef.value.getCurRow(),
    curIndex = dataListRef.value.getCurIndex();
  if (curRow != null && curIndex != -1) {
    dataListRef.value.onCancel(curRow, curIndex);
  }
};
const saveTableDatas = () => {
  localStorage.setItem("SDID", JSON.stringify(tableDatas.array));
  console.log("save datas");
};
const loadTableDatas = () => {
  console.log("load datas");
  const savedData = localStorage.getItem("SDID");
  if (savedData) {
    tableDatas.array = JSON.parse(savedData);
  } else {
    console.log("load data failed");
  }
};

const downloadTableData = e => {
  const duration = ref(999999)
  message("正在从云端下载数据中...", {
    type: "info",
    customClass: "antd",
  });
  message("下载成功", {
    type: "success",
    customClass: "antd"
  });
};
const uploadTableData = e => {
  message("正在上传到云端中...", {
    type: "info",
    customClass: "antd"
  });
  message("上传成功", {
    type: "success",
    customClass: "antd"
  });
};

const loadLogInfo = async () => {
  const convertTimestampToTime = (yearHead, timeStamp) => {
    const year = timeStamp.slice(0, 2);
    const month = timeStamp.slice(2, 4);
    const day = timeStamp.slice(4, 6);
    const hours = timeStamp.slice(6, 8);
    const minutes = timeStamp.slice(8, 10);
    const seconds = timeStamp.slice(10, 12);
    return `${yearHead}${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  const params = {
    limit: 10,
    path: "kafka/topicDataLake2-json"
  };
  await axios
    .post("http://10.8.58.1:8400/sparkData/query", params)
    .then(res => {
      const logInfos = res.data.data.data.sort(
        (a, b) => a.timeStamp - b.timeStamp
      );
      for (let item of logInfos) {
        logDatas.array.unshift({
          timeStamp: convertTimestampToTime("20", item.timeStamp),
          topic: topic,
          ip: ip.split(":")[0],
          port: ip.split(":")[1],
          fileName: item.fileName,
          dataCode: item.dataCode
        });
      }
      // console.log(logDatas);
    });
};
onMounted(() => {
  syncData();
  loadTableDatas();
  loadLogInfo();
});
onUnmounted(() => {
  saveTableDatas();
});
watch(tableDatas, newProps => {
  syncData();
  saveTableDatas();
});
</script>

<template>
  <!-- 点击编辑弹出框 -->
  <el-dialog v-model="editTable" @close="closeEdit">
    <EditTable
      ref="dataListRef"
      :dataList="dataList"
      :columnsName="columnsName"
    />
  </el-dialog>

  <!-- 主页面 -->
  <el-row :gutter="20">
    <el-col :span="12" style="min-height: 200px">
      <FormInfo
        :title="formProps1.title"
        :btnNames="formProps1.btnNames"
        :btnDisabled="formProps1.btnDisabled"
        :formInfoList="formProps1.formInfoList"
        @btnClick1="formBtnClick"
      >
        <template #afc1>
          <el-contaienr>
            <el-main class="identification-main">
              <div class="mb-[20px]"><span>远程kafka服务器设置</span></div>
              <FormInfoInput
                ref="kafkaConfig"
                v-for="item in formProps2.formInfoList"
                :key="item.id"
                :title="item.title"
                :options="item.options"
                :inputType="item.inputType"
              />
              <el-col :span="5" :offset="19">
                <el-button
                  class="afc1-btn"
                  type="primary"
                  @click="drawerVisible = !drawerVisible"
                >
                  标识配置映射表
                </el-button>
              </el-col>
            </el-main>
          </el-contaienr>
        </template>
        <template #afc2>
          <el-col class="afc2-input" :span="24">
            <FormInfoInput ref="SDID" title="数据标识" inputType="2" />
          </el-col>
        </template>
      </FormInfo>
    </el-col>
    <el-col :span="12" style="min-height: 200px">
      <InfoContainer :title="leftContentTitle">
        <el-scrollbar ref="scrollBarRef" height="82vh">
          <div ref="innerBarRef">
            <Log
              v-for="(item, index) in logDatas.array"
              :key="index"
              :log="item"
            />
          </div>
        </el-scrollbar>
      </InfoContainer>
    </el-col>
    <!-- 这个div用来改el-drawer的样式，不要删 -->
    <div>
      <el-drawer v-model="drawerVisible" :with-header="true">
        <!-- 标题 -->
        <template v-slot:header>
          <div class="custom-header">
            <el-row>
              <el-col :span="16">
                <span>{{ drawer_props.title }}</span>
              </el-col>
              <el-col class="drawer-header-btn" :span="4">
                <el-button type="success" @click="downloadTableData">
                  下载<el-icon class="el-icon--right"><Download /></el-icon>
                </el-button>
                <el-tooltip :content="downLoadToolTip" placement="top">
                  <h3 style="color: rgb(103, 194, 58)">
                    <Icon icon="tdesign:help-circle" />
                  </h3>
                </el-tooltip>
              </el-col>
              <el-col class="drawer-header-btn" :span="4">
                <el-button type="primary" @click="uploadTableData">
                  上传<el-icon class="el-icon--right"><Upload /></el-icon>
                </el-button>
                <el-tooltip :content="upLoadToolTip" placement="top">
                  <h3 style="color: rgb(64, 158, 255)">
                    <Icon icon="tdesign:help-circle" />
                  </h3>
                </el-tooltip>
              </el-col>
            </el-row>
          </div>
        </template>
        <MatchTable
          v-for="(item, index) in tableDatas.array"
          :colInfo="item.colInfo"
          :tableData="item.tableData"
          @btnClick1="tableBtnClick(index)"
        />
      </el-drawer>
    </div>
  </el-row>
</template>
<style lang="scss" scoped>
:deep(.el-overlay) {
  position: static !important;
}
:deep(.el-drawer) {
  width: 49.3% !important;
  height: 93.5vh !important;
  border-radius: 10px;
  border: 1px solid #dcdfe6;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1) !important;
}
:deep(.el_drawer:hover) {
  box-shadow: 0 5px 12px 0 rgba(0, 0, 0, 0.3) !important;
}
:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
  height: 6.78vh !important;
  border-bottom: 1px solid #ccc !important;
  padding-top: 0;
}
:deep(.el-drawer__body) {
  padding-top: 0;
}

.identification-main {
  // height: 58vh;
  background-color: rgb(250, 250, 250);
  border-radius: 6px;
  display: flex;
  flex-flow: column;
  justify-content: space-around;
  span {
    font-weight: bold;
  }
  .el-col {
    padding: 0px !important;
  }
  .afc1-btn {
    width: 100%;
    margin: 0 !important;
  }
}
.afc2-input {
  margin-top: 1vh;
}

.custom-header {
  background-color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  .drawer-header-btn {
    height: 24px;
    padding-right: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
</style>
